package com.example.letgo.Fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.letgo.R;
import com.example.letgo.global.Constant;
import com.example.letgo.tool.CircleTransform;
import com.example.letgo.model.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.zaaach.toprightmenu.MenuItem;
import com.zaaach.toprightmenu.TopRightMenu;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import okhttp3.Call;
import okhttp3.Response;


/**
 * Created by cc on 2018/2/3.
 */

public class InformationFragment extends android.support.v4.app.Fragment{
    private android.support.v4.app.Fragment mConversationFragment=null;
    private PagerAdapter mFragmentPagerAdapter;
    private List<android.support.v4.app.Fragment> mFragment = new ArrayList<>();

    private Toolbar toolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private ListView lvLeftMenu;
    private String[] lvs = {"消息列表", "添加请求", "朋友列表", "群组信息"};
    private ArrayAdapter arrayAdapter;
    private LinearLayout Linform,LnewFriend,Lfriends,Lteam;
    ListView listFriends;
    ImageView imageView;
    TextView tv_name,tv_sign;

    private TopRightMenu mTopRightMenu;

    public InformationFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_information, container, false);
        //---这是侧滑的开始
        getControl(view);
        //设置菜单列表
        getConversationList(view);
        //Test
//        getClick(view);
        //设置朋友列表
        getFriendsList(view);

        //开始多人聊天
        chatMany(view);

        Log.i("ID",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>    "+Constant.id);

        return view;
    }

    private void chatMany(View view) {
        final ImageView imageAdd = view.findViewById(R.id.seal_more);
        imageAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mTopRightMenu = new TopRightMenu(getActivity());
                List<MenuItem> menuItems = new ArrayList<>();
                menuItems.add(new MenuItem(R.mipmap.multichat, "发起多人聊天"));
                menuItems.add(new MenuItem(R.mipmap.addmember, "发起私人聊天"));
                mTopRightMenu
                        .setHeight(200)     //默认高度480
                        .setWidth(320)      //默认宽度wrap_content
                        .showIcon(true)     //显示菜单图标，默认为true
                        .dimBackground(true)           //背景变暗，默认为true
                        .needAnimationStyle(true)   //显示动画，默认为true
                        .setAnimationStyle(R.style.TRM_ANIM_STYLE)  //默认为R.style.TRM_ANIM_STYLE
                        .addMenuList(menuItems)
                        .setOnMenuItemClickListener(new TopRightMenu.OnMenuItemClickListener() {
                            @Override
                            public void onMenuItemClick(int position) {
                                Toast.makeText(getActivity(), "点击菜单:" + position, Toast.LENGTH_SHORT).show();
                            }
                        })
                        .showAsDropDown(imageAdd, -225, 0);
            }
        });
    }

    private void getFriendsList(final View view) {
        //获取当前id的用户的所有好友，此处id为2
        int userId = Constant.id;
        OkGo.get("http://www.mfcsjk.com/get?id=591")
                .params("userId",userId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e("s",s);
                        Gson gson = new Gson();
                        Type listType = new TypeToken<LinkedList<User>>(){}.getType();
                        LinkedList<User> lists = gson.fromJson(s, listType);
                        for (int i = 0;i<lists.size();i++){
                            Log.e("i>>>", String.valueOf(lists.get(i).getUserId()));
                        }
                        //生成setAdapter的方法，并将数据传进去
                        lvSetAdapter(lists,view);
                    }
                });
    }
    //生成setAdapter的方法，并将数据传进去
    private void lvSetAdapter(final LinkedList<User> lists, View view) {
        listFriends = view.findViewById(R.id.F_lv);
        listFriends.setAdapter(new MyAdapter(lists));
        listFriends.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.e("i",String.valueOf(i));
                Log.e("id",String.valueOf(lists.get(i).getUserId()));
                RongIM.getInstance().refreshUserInfoCache(new UserInfo(String.valueOf(lists.get(i).getUserId()),lists.get(i).getUserNickName(),Uri.parse(lists.get(i).getUserImg())));
                RongIM.getInstance().startPrivateChat(getActivity(), String.valueOf(lists.get(i).getUserId()),lists.get(i).getUserNickName());
            }
        });

    }
//
//    private void getClick(View view) {
//        Button btn = view.findViewById(R.id.btnTest);
//        btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                RongIM.getInstance().startPrivateChat(getActivity(),"2","私人聊天");
//            }
//        });
//    }

    private void getConversationList(View view) {
        arrayAdapter = new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, lvs);
        lvLeftMenu.setAdapter(arrayAdapter);
        //listview的点击事件切换页面
        lvLeftMenu.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i){
                    case 0:
                        Linform.setVisibility(View.VISIBLE);
                        LnewFriend.setVisibility(View.INVISIBLE);
                        Lfriends.setVisibility(View.INVISIBLE);
                        Lteam.setVisibility(View.INVISIBLE);
                        //设置toolbar的相关信息
                        toolbar.setTitle("消息");
                        break;
                    case 1:
                        Linform.setVisibility(View.INVISIBLE);
                        LnewFriend.setVisibility(View.VISIBLE);
                        Lfriends.setVisibility(View.INVISIBLE);
                        Lteam.setVisibility(View.INVISIBLE);
                        //设置toolbar的相关信息
                        toolbar.setTitle("新朋友");
                        break;
                    case 2:
                        Linform.setVisibility(View.INVISIBLE);
                        LnewFriend.setVisibility(View.INVISIBLE);
                        Lfriends.setVisibility(View.VISIBLE);
                        Lteam.setVisibility(View.INVISIBLE);
                        //设置toolbar的相关信息
                        toolbar.setTitle("好友列表");
                        break;
                    case 3:
                        Linform.setVisibility(View.INVISIBLE);
                        LnewFriend.setVisibility(View.INVISIBLE);
                        Lfriends.setVisibility(View.INVISIBLE);
                        Lteam.setVisibility(View.VISIBLE);
                        //设置toolbar的相关信息
                        toolbar.setTitle("群组");
                        break;

                }
            }
        });
        //------以下是聊天界面的list
        mConversationFragment = initConversationList();
        ViewPager mViewPager = view.findViewById(R.id.main_viewpager);
        //将所有的fragment实例化到mfragment里面
        mFragment.add(mConversationFragment);
        mFragmentPagerAdapter = new FragmentPagerAdapter(getFragmentManager()) {
            @Override
            public android.support.v4.app.Fragment getItem(int position) {
                return mFragment.get(position);
            }
            @Override
            public int getCount() {
                return mFragment.size();
            }
        };
        mViewPager.setAdapter(mFragmentPagerAdapter);
    }

    //---这是侧滑的开始
    private void getControl(View view) {
        toolbar = view.findViewById(R.id.tl_custom);
        mDrawerLayout = view.findViewById(R.id.dl_left);
        lvLeftMenu = view.findViewById(R.id.lv_left_menu);
        Linform = view.findViewById(R.id.informList);
        LnewFriend = view.findViewById(R.id.newFriend);
        Lfriends = view.findViewById(R.id.friendsList);
        Lteam = view.findViewById(R.id.TeamsList);
        //设置toolbar的相关信息
        toolbar.setTitle("消息");
        toolbar.setTitleTextColor(Color.parseColor("#ffffff"));
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        ((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout,toolbar,R.string.open,R.string.close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        mDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    //列表的注册初始化，这样就不用去配置文件中配置了
    private android.support.v4.app.Fragment initConversationList(){
        if (mConversationFragment==null){
            Uri uri;
            uri=Uri.parse("rong://" + getActivity().getApplicationInfo().packageName).buildUpon()
                    .appendPath("conversationlist")
                    .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话是否聚合显示
                    .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "true")//群组
                    .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "false")//系统
                    .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "false")//私聊是否聚合
                    .build();

            ConversationListFragment listFragment = new ConversationListFragment();
            listFragment.setUri(uri);
            mConversationFragment = listFragment;
            return listFragment;
        }else {
            return mConversationFragment;
        }
    }

    //用于item和lsitvie之间的关系
    class MyAdapter extends BaseAdapter {

        LinkedList<User> userlists;
        public MyAdapter(LinkedList<User> lists) {
            this.userlists = lists;
        }

        //item的总数
        @Override
        public int getCount() {
            return userlists.size();
        }
        //获取item本身的对象
        @Override
        public Object getItem(int position) {
            return userlists.get(position);
        }
        //获取item的id值
        @Override
        public long getItemId(int position) {
            return position;
        }
        //获取item的子布局
        @SuppressLint("RestrictedApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(getActivity(),R.layout.fragment_information_friendslist_item,null);
            imageView = view.findViewById(R.id.imgv);
            tv_name = view.findViewById(R.id.tv_name);
            tv_sign = view.findViewById(R.id.tv_sign);

            //判断获取的json中图片是否为空
            if (TextUtils.isEmpty(userlists.get(position).getUserImg())){
                Picasso
                        .with(getActivity())
                        .cancelRequest(imageView);
                imageView.setImageDrawable(getResources().getDrawable(R.drawable.head));//当图片为空时显示
            }else {
                //图片加载
                Picasso.with(getActivity()).load(userlists.get(position).getUserImg())
                        .transform(new CircleTransform())
                        .into(imageView);
            }
            tv_name.setText(userlists.get(position).getUserNickName());
            tv_sign.setText(userlists.get(position).getUserSign());
            return view;
        }
    }
}
